<template>
  <div class="literature">
    <!-- 头部导航 -->
    <div class="header">
      <el-button @click="goBack" type="primary" plain>
        <el-icon><ArrowLeft /></el-icon>
        返回主页
      </el-button>
      <h1 class="title">文献详情</h1>
    </div>

    <!-- 筛选条件 -->
    <div class="filter-section">
      <el-card class="filter-card">
        <div class="filter-content">
          <div class="filter-item">
            <span class="filter-label">朝代：</span>
            <el-select 
              v-model="selectedDynastyId" 
              placeholder="选择朝代"
              @change="onDynastyChange"
              clearable
            >
              <el-option
                v-for="dynasty in dynasties"
                :key="dynasty.dynastyId"
                :label="dynasty.dynastyName"
                :value="String(dynasty.dynastyId)"
              />
            </el-select>
          </div>
          <div class="filter-item">
            <span class="filter-label">地区：</span>
            <el-select 
              v-model="selectedRegionId" 
              placeholder="选择地区"
              @change="onRegionChange"
              clearable
            >
              <el-option
                v-for="region in regions"
                :key="region.regionId"
                :label="region.regionName"
                :value="String(region.regionId)"
              />
            </el-select>
          </div>
          <div class="filter-item">
            <span class="filter-label">文献类型：</span>
            <el-select 
              v-model="selectedType" 
              placeholder="选择类型"
              @change="onTypeChange"
              clearable
            >
              <el-option label="史志" value="史志" />
              <el-option label="考古报告" value="考古报告" />
              <el-option label="工艺专著" value="工艺专著" />
              <el-option label="艺术评论" value="艺术评论" />
              <el-option label="学术论文" value="学术论文" />
              <el-option label="技术研究" value="技术研究" />
              <el-option label="艺术研究" value="艺术研究" />
              <el-option label="传承记录" value="传承记录" />
              <el-option label="工艺介绍" value="工艺介绍" />
              <el-option label="文化研究" value="文化研究" />
            </el-select>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 文献列表 -->
    <div class="literature-section">
      <el-card class="literature-card">
        <template #header>
          <div class="card-header">
            <span>文献列表</span>
            <span class="count">共 {{ filteredLiteratures.length }} 篇</span>
          </div>
        </template>
        
        <div v-if="loading" class="loading">
          <el-skeleton :rows="3" animated />
        </div>
        
        <div v-else-if="filteredLiteratures.length === 0" class="empty">
          <el-empty description="暂无相关文献" />
        </div>
        
        <div v-else class="literature-list">
          <div
            v-for="literature in filteredLiteratures"
            :key="literature.literatureId"
            class="literature-item"
            :class="{ active: selectedLiterature?.literatureId === literature.literatureId }"
            @click="selectLiterature(literature)"
          >
            <div class="literature-header">
              <h3 class="literature-title">{{ literature.title }}</h3>
              <div class="literature-meta">
                <span class="author">{{ literature.author }}</span>
                <span class="type">{{ literature.literatureType }}</span>
              </div>
            </div>
            <div class="literature-summary">
              {{ literature.summary }}
            </div>
            <div class="literature-tags">
              <el-tag 
                v-for="keyword in literature.keywords?.split(',')" 
                :key="keyword"
                size="small"
                type="info"
              >
                {{ keyword }}
              </el-tag>
            </div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 文献详情 -->
    <div v-if="selectedLiterature" class="detail-section">
      <el-card class="detail-card">
        <template #header>
          <div class="card-header">
            <span>文献详情</span>
            <el-button @click="selectedLiterature = null" type="text">
              <el-icon><Close /></el-icon>
            </el-button>
          </div>
        </template>
        
        <div class="detail-content">
          <h2 class="detail-title">{{ selectedLiterature.title }}</h2>
          <div class="detail-meta">
            <p><strong>作者：</strong>{{ selectedLiterature.author }}</p>
            <p><strong>类型：</strong>{{ selectedLiterature.literatureType }}</p>
            <p><strong>来源：</strong>{{ selectedLiterature.source }}</p>
            <p><strong>关键词：</strong>{{ selectedLiterature.keywords }}</p>
          </div>
          <div class="detail-summary">
            <h3>摘要</h3>
            <p>{{ selectedLiterature.summary }}</p>
          </div>
          <div class="detail-content-text">
            <h3>全文内容</h3>
            <div class="content-text">{{ selectedLiterature.content }}</div>
          </div>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { dynastyApi } from '@/api/dynasty'
import { regionApi } from '@/api/region'
import { literatureApi } from '@/api/literature'

export default {
  name: 'Literature',
  setup() {
    const router = useRouter()
    const route = useRoute()
    
    const dynasties = ref([])
    const regions = ref([])
    const literatures = ref([])
    const selectedDynastyId = ref('')
    const selectedRegionId = ref('')
    const selectedType = ref('')
    const selectedLiterature = ref(null)
    const loading = ref(false)

    // 根据筛选条件过滤文献
    const filteredLiteratures = computed(() => {
      let filtered = literatures.value

      if (selectedDynastyId.value) {
        filtered = filtered.filter(item => String(item.dynastyId) === selectedDynastyId.value)
      }

      if (selectedRegionId.value) {
        filtered = filtered.filter(item => String(item.regionId) === selectedRegionId.value)
      }

      if (selectedType.value) {
        filtered = filtered.filter(item => item.literatureType === selectedType.value)
      }

      return filtered
    })

    // 获取朝代数据
    const fetchDynasties = async () => {
      try {
        const response = await dynastyApi.getAllDynasties()
        if (response.code === 0) {
          dynasties.value = response.data
        }
      } catch (error) {
        ElMessage.error('获取朝代数据失败')
        console.error(error)
      }
    }

    // 获取地区数据
    const fetchRegions = async () => {
      try {
        const response = await regionApi.getAllRegions()
        if (response.code === 0) {
          regions.value = response.data
        }
      } catch (error) {
        ElMessage.error('获取地区数据失败')
        console.error(error)
      }
    }

    // 获取文献数据
    const fetchLiteratures = async () => {
      try {
        loading.value = true
        let response

        if (selectedDynastyId.value && selectedRegionId.value) {
          response = await literatureApi.getLiteraturesByDynastyAndRegion(
            selectedDynastyId.value, 
            selectedRegionId.value
          )
        } else if (selectedDynastyId.value) {
          response = await literatureApi.getLiteraturesByDynasty(selectedDynastyId.value)
        } else if (selectedRegionId.value) {
          response = await literatureApi.getLiteraturesByRegion(selectedRegionId.value)
        } else {
          // 如果没有筛选条件，获取所有文献（这里需要后端提供获取所有文献的接口）
          // 暂时使用空数组
          literatures.value = []
          return
        }

        if (response.code === 0) {
          literatures.value = response.data
        }
      } catch (error) {
        ElMessage.error('获取文献数据失败')
        console.error(error)
      } finally {
        loading.value = false
      }
    }

    // 朝代变化
    const onDynastyChange = () => {
      fetchLiteratures()
    }

    // 地区变化
    const onRegionChange = () => {
      fetchLiteratures()
    }

    // 类型变化
    const onTypeChange = () => {
      // 类型筛选不需要重新请求，使用computed过滤
    }

    // 选择文献
    const selectLiterature = (literature) => {
      selectedLiterature.value = literature
    }

    // 返回主页
    const goBack = () => {
      router.push('/')
    }

    // 监听路由参数变化
    watch(() => route.query, (query) => {
      if (query.dynastyId) {
        selectedDynastyId.value = query.dynastyId
      }
      if (query.regionId) {
        selectedRegionId.value = query.regionId
      }
    }, { immediate: true })

    // 监听筛选条件变化
    watch([selectedDynastyId, selectedRegionId], () => {
      if (selectedDynastyId.value || selectedRegionId.value) {
        fetchLiteratures()
      }
    })

    onMounted(() => {
      fetchDynasties()
      fetchRegions()
    })

    return {
      dynasties,
      regions,
      literatures,
      selectedDynastyId,
      selectedRegionId,
      selectedType,
      selectedLiterature,
      filteredLiteratures,
      loading,
      onDynastyChange,
      onRegionChange,
      onTypeChange,
      selectLiterature,
      goBack
    }
  }
}
</script>

<style scoped>
.literature {
  min-height: 100vh;
  padding: 20px;
}

.header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  gap: 20px;
}

.title {
  color: #fff;
  font-size: 2rem;
  margin: 0;
}

.filter-section {
  margin-bottom: 20px;
}

.filter-card {
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.filter-content {
  display: flex;
  gap: 20px;
  align-items: center;
  flex-wrap: wrap;
}

.filter-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.filter-label {
  color: #fff;
  font-weight: 500;
  white-space: nowrap;
}

/* 为筛选框添加宽度 */
.filter-item .el-select {
  width: 200px;
}

/* 文献类型选择器可以稍宽一些 */
.filter-item:last-child .el-select {
  width: 220px;
}

.literature-section {
  margin-bottom: 20px;
}

.literature-card {
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: #fff;
}

.count {
  font-size: 0.9rem;
  color: rgba(255, 255, 255, 0.7);
}

.loading {
  padding: 20px;
}

.empty {
  padding: 40px;
}

.literature-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.literature-item {
  background: rgba(255, 255, 255, 0.05);
  border-radius: 8px;
  padding: 20px;
  cursor: pointer;
  transition: all 0.3s ease;
  border: 1px solid rgba(255, 255, 255, 0.1);
}

.literature-item:hover {
  background: rgba(255, 255, 255, 0.1);
  transform: translateY(-2px);
}

.literature-item.active {
  background: rgba(64, 158, 255, 0.2);
  border-color: #409eff;
}

.literature-header {
  margin-bottom: 10px;
}

.literature-title {
  color: #fff;
  font-size: 1.2rem;
  margin-bottom: 8px;
}

.literature-meta {
  display: flex;
  gap: 15px;
  font-size: 0.9rem;
}

.author {
  color: #409eff;
}

.type {
  color: #67c23a;
}

.literature-summary {
  color: rgba(255, 255, 255, 0.8);
  line-height: 1.6;
  margin-bottom: 10px;
}

.literature-tags {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.detail-section {
  margin-top: 20px;
}

.detail-card {
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.detail-content {
  color: #fff;
}

.detail-title {
  font-size: 1.8rem;
  margin-bottom: 20px;
  color: #fff;
}

.detail-meta {
  background: rgba(255, 255, 255, 0.05);
  border-radius: 8px;
  padding: 15px;
  margin-bottom: 20px;
}

.detail-meta p {
  margin-bottom: 8px;
  line-height: 1.6;
}

.detail-meta strong {
  color: #409eff;
}

.detail-summary,
.detail-content-text {
  margin-bottom: 20px;
}

.detail-summary h3,
.detail-content-text h3 {
  color: #409eff;
  margin-bottom: 10px;
  font-size: 1.2rem;
}

.detail-summary p,
.content-text {
  line-height: 1.8;
  color: rgba(255, 255, 255, 0.9);
  text-align: justify;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .filter-content {
    flex-direction: column;
    align-items: stretch;
  }
  
  .filter-item {
    justify-content: space-between;
  }
  
  .literature-meta {
    flex-direction: column;
    gap: 5px;
  }
}
</style> 